<template>
  <div class="shoppingcartContent">
    <el-table
      :data="goodsList"
      stripe
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      empty-text="购物车空空如也"
      @select="select"
      @select-all="select"
      @selection-change="select"
    >
      <el-table-column type="selection"> </el-table-column>

      <el-table-column label="商品图片">
        <template #default="{ row }">
          <el-image :src="row.product.goodsThumbnailImg"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称">
        <template #default="{ row }">
          <span>{{ row.product.goodsName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品单价">
        <template #default="{ row }">
          <span>￥{{ row.product.goodsPrice }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="count" label="商品数量">
        <template #default="{ row }">
          <el-input-number
            v-model="row.count"
            :min="1"
            :max="999"
            size="mini"
            @change="updateCount(row)"
          ></el-input-number>
        </template>
      </el-table-column>

      <el-table-column prop="price" label="小计">
        <template #default="{ row }">
          <span>￥{{ row.product.goodsPrice * row.count }} </span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button size="mini" type="danger" @click="deleteProduct(scope)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="ShoppingCartBottom">
      <div>
        <!-- <el-button type="primary" @click="deleteMultipleProduct()">删除选择项</el-button> -->
      </div>

      <div class="settlement">
        <p class="totalPrice">已选择{{ selectCount }}件商品</p>
        <p class="totalPrice">总价格为：￥{{ totalPrice }}</p>
        <el-button type="success" @click="openCreateOrder()">结算</el-button>
      </div>
    </div>
  </div>
  <div v-if="isCreateOrder" class="createOrder">
    <h2>创建订单</h2>
    <el-form
      :label-position="top"
      label-width="80px"
      style="margin-top: 30px"
      :model="order"
    >
      <el-form-item label="收件地址">
        <el-input v-model="order.address"></el-input>
      </el-form-item>
      <el-form-item label="收件人">
        <el-input v-model="order.recevier"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="order.phoneNumber"></el-input>
      </el-form-item>
    </el-form>

    <div class="choose">
      <div class="totalPrice"><span>总价格为：￥{{ totalPrice }}</span> </div>
      <div >
        <el-button @click="cancelCreateOrder()">取消</el-button>
        <el-button type="primary" @click="createOrder()">确认</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserShoppingCart } from "@/apis/getData.js";
import { updateProductCountFromShopcart } from "@/apis/updateData.js";
import { deleteProductFromShopCart } from "@/apis/deleteData.js";
import { insertOrder, insertOrderDetail } from "@/apis/insertData.js";
import { onMounted, ref, computed, reactive } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
export default {
  name: "ShoppingCart",

  setup() {
    const goodsList = ref([]);
    const islogin = ref(false);
    const store = useStore(); // 使用useStore方法
    const selectCount = ref(0);
    const selectList = ref([]);
    const router = useRouter();
    const uid = ref(1);
    const isCreateOrder = ref(false);
    const addresses = ref([]);
    const order = reactive({
      phoneNumber: "",
      address: "",
      recevier: "",
    });

    onMounted(() => {
      addresses.value = loadUserAddress();
      if (store.getters.getUser == null) {
        router.push("/login");
      } else {
        uid.value = store.getters.getUser.uid;
        getShopCartData();
      }
    });

    const loadUserAddress = () => {
      return [{ value: "广州市" }, { value: "揭阳市" }];
    };
    //  赛选输入的地址
    const querySearch = (queryString, cb) => {
      var results = queryString
        ? addresses.value.filter(createFilter(queryString))
        : addresses.value;
      // 调用 callback 返回建议列表的数据
      cb(results);
    };
    const createFilter = (queryString) => {
      return (address) => {
        return (
          address.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    };
    //  获取商品购物车信息
    function getShopCartData() {
      let params = new FormData();
      params.append("uid", uid.value);
      getUserShoppingCart(params).then((res) => {
        goodsList.value = res.data.data;
      });
    }
    //  检测登陆
    function checkLoging() {
      if (store.getters.getUser == null) {
        islogin.value = false;
      } else {
        getShopCartData();
        islogin.value = true;
      }
    }
    //  选中商品的总价格
    const totalPrice = computed(() => {
      let result = 0;
      if (selectList.value.length <= 0) {
        return 0;
      }
      selectList.value.forEach((goods) => {
        result = result + goods.product.goodsPrice * goods.count;
      });
      return result;
    });

    //  获取选中商品的数据
    function select(selection) {
      console.log(selection);
      selectCount.value = selection.length;
      selectList.value = selection;
    }

    //  更新商品数量到数据库
    function updateCount(row) {
      let params = new FormData();
      params.append("uid", uid.value);
      params.append("gid", row.gid);
      params.append("count", row.count);
      updateProductCountFromShopcart(params).then((res) => {
        if (res.data.data > 0) {
          console.log(res.data.message);
        } else {
          console.log("更新商品数量失败！");
        }
      });
    }
    //  删除商品
    function deleteProduct(scope) {
      let params = new FormData();
      params.append("uid", uid.value);
      params.append("gid", scope.row.gid);
      deleteProductFromShopCart(params).then((res) => {
        if (res.data.data > 0) {
          goodsList.value.splice(scope.$index, 1);
          console.log(res.data.message);
        } else {
          console.log("删除商品失败！");
        }
      });
    }
    //  删除选择的商品
    function deleteMultipleProduct() {
      selectList.value.forEach((product) => {
        let params = new FormData();
        params.append("uid", uid.value);
        params.append("gid", product.gid);
        deleteProductFromShopCart(params).then((res) => {
          if (res.data.data > 0) {
            console.log(res.data.message);
          } else {
            console.log("删除商品失败！");
          }
        });
      });
    }

    //  创建订单
    function createOrder() {
      let orderParm = new FormData();
      orderParm.append("uid", uid.value);
      orderParm.append("sum", totalPrice.value);
      orderParm.append("phone", order.phoneNumber);
      orderParm.append("receiver", order.recevier);
      orderParm.append("address", order.address);
      console.log(
        order.phoneNumber + " " + order.recevier + " " + order.address
      );
      insertOrder(orderParm).then((res) => {
        if (selectList.value.length > 0) {
          selectList.value.forEach((product) => {
            let OrderDetail = new FormData();
            OrderDetail.append("oid", res.data.data);
            OrderDetail.append("gid", product.product.gid);
            OrderDetail.append("count", product.count);
            insertOrderDetail(OrderDetail);
          });
          isCreateOrder.value = false;
          deleteMultipleProduct(); // 删除选择的商品
          gotoOrderList();
          ElMessage.success({
            message: "订单创建成功",
            type: "success",
          });
        } else {
          ElMessage.warning({
            message: "请选择商品！",
            type: "warning",
          });
        }
      });
    }
    //  打开订单创建窗口
    function openCreateOrder() {
      isCreateOrder.value = true;
    }
    //  关闭订单创建窗口
    function cancelCreateOrder() {
      isCreateOrder.value = false;
    }
    //  跳转订单页面
    function gotoOrderList() {
      router.push("/OrderList");
    }

    return {
      goodsList,
      islogin,
      totalPrice,
      checkLoging,
      selectCount,
      select,
      updateCount,
      deleteProduct,
      //deleteMultipleProduct,
      createOrder,
      openCreateOrder,
      cancelCreateOrder,
      gotoOrderList,
      isCreateOrder,
      loadUserAddress,
      querySearch,
      order,
    };
  },
  methods: {},
};
</script>

<style scoped>
.shoppingcartContent {
  margin: 0 auto;
  width: 990px;
}
.goods {
  display: flex;
  justify-content: left;
}
.ShoppingCartBottom {
  display: flex;
  padding-top: 25px;
  justify-content: space-between;
  padding: 25px 40px;
}
.ShoppingCartBottom .settlement {
  display: flex;
  justify-content: flex-end;
}
.ShoppingCartBottom .settlement .totalPrice {
  display: flex;
  margin-right: 50px;
  align-items: center;
}
.createOrder {
  z-index: 100;
  background: rgb(255, 255, 255);
  border: 1px solid gainsboro;
  border-radius: 5px;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-left: -200px;
  margin-top: -150px;
  width: 400px;
  height: 300px;
  padding: 15px;
}
.createOrder .choose {
  display: flex;
  justify-content: right;
  margin-top: 20px;
}
.createOrder .choose .totalPrice{
  display: flex;
  align-items: center;
  margin-right: 15px;
}
</style>
